//监控类型
const camtypes = {
	rtc: "rtc", //rtsp
	flv_hls: "flv_hls",
}

//当前使用类型
const use = camtypes.rtc;

var _wh = -1;
var _isDone = false;
/**
 * ----------------------------------- rtc    --------------------
 */

function hWaitWebRtc() {
	clearTimeout(_wh);
	if (typeof(WebRtcPlayer) != typeof(undefined) && !_isDone) {
		// WebRtcPlayer.setServer('192.168.1.252:8083');
		WebRtcPlayer.setServer('192.168.12.180:8083');
		console.log("WebRtcPlayer done.");
		_isDone = true;
	} else {
		_wh = setTimeout(function() {
			hWaitWebRtc();
		}, 3000);
	}
}

function createVideoDom(id) {

	id = id || "cam_" + Date.now();

	var html = `<button onclick="ClosePanel('${id}')"> X </button>
				<video class="videoPlayer" id="v1_${id}" controls muted loop autoplay></video> `;

	var doms = document.createElement("div");
	doms.setAttribute("id", id);
	doms.setAttribute("class", 'panel');
	doms.innerHTML = html;
	document.body.appendChild(doms);
	return doms;
}
//rtsp://admin:aa123456@192.168.1.68/Streaming/Channels/101?transportmode=unicast
/**
 * ----------------------------flv      hls        ----------------------
 */

//var hlsTemplate="http://{0}:7086/live/cameraid/{1}%24{2}/substream/{3}.m3u8";
//var hlsHttpsTemplate="https://{0}:7096/live/cameraid/{1}%24{2}/substream/{3}.m3u8";
//var flvTemplate="http://{0}:7886/live/cameraid/{1}%24{2}/substream/{3}.flv";
//var flvHttpsTemplate="https://{0}:7896/live/cameraid/{1}%24{2}/substream/{3}.flv";
//var flv = String.format(flvTemplate, ip, deviceCode, channelSeq, sustreamType);
String.format = function(src) {
	if (arguments.length == 0) return null;
	var args = Array.prototype.slice.call(arguments, 1);
	return src.replace(/\{(\d+)\}/g, function(m, i) {
		return args[i];
	});
};

function hWaitFlvHls() {
	if ((typeof(flvjs) != typeof(undefined) || typeof(Hls) != typeof(undefined)) &&
		!_isDone) {
		clearTimeout(_wh);
		_isDone = true;
	} else {
		_wh = setTimeout(function() {
			hWaitFlvHls();
		}, 3000);
	}
}



function ShowPanel(id) {
	var dom = document.querySelector("#" + id);
	dom.setAttribute("style", "display:block;");
}

function ClosePanel(id) {
	var dom = document.querySelector("#" + id);
	dom.setAttribute("style", "display:none;");
	let vid = dom.getElementsByTagName("video")[0].id;

	hClearFlvHls(vid);


	for (var i = 0; i < v2s.length; i++) {
		if (v2s[i].id == id) {
			v2s[i].video.destroy();
		}
	}
	for (var i = 0; i < players.length; i++) {
		if (players[i].id == id) {
			players[i].video.destroy();
			break;
		}
	}
}

window.players = [];


/**
 * @param {Object} id dom id
 * @param {Object} p {x:0,y:0}
 */
function SetPos(id, p) {
	var dom = document.querySelector("#" + id);
	var t = `left:${p.x}px;top:${p.y}px`;
	//`transform: translate();`
	dom.setAttribute("style", t);
}

/**
 * @param {Object} domId  video dom id
 * @param {Object} code
 * @param {Object} st  1主码  2辅码
 * @param {Object} host 主机地址
 */
function PlayVideoDom(domId, code, st, host) {
	let dom = document.querySelector("#" + domId);
	if (!dom) {
		console.log("dom 未就绪无法播放", domId, code, host)
		return;
	}
	if (use == camtypes.flv_hls) {
		hHlsPlay(host, code, dom, st);
		return dom;
	}
	var v = players.find((t) => t.id == domId);
	if (!v) {
		if (host) {
			WebRtcPlayer.setServer(host);
		}
		var wv = new WebRtcPlayer(domId, 'demo');
		v = {
			id: domId,
			video: wv
		};
		players.push(v);

	}
	if (code) {
		try {
			v.video.load(code);
		} catch (e) {
			//TODO handle the exception
		}
	}
	return dom;
}

function PlayVideo(vDomId, camCode, host) {
	var id = "v1_" + vDomId;
	var dom = document.querySelector("#" + id);
	if (!dom) {
		dom = createVideoDom(id);
		dom.addEventListener("mousedown", hMouseDown, false);
	}
	ShowPanel(id);
	let vid = dom.getElementsByTagName("video")[0].id;
	return PlayVideoDom(vid, camCode, 1, host);
}
var v2s = [];
/**
 * @param {Object} dats [{id:0,code:""}]
 * @param {Object} host ip
 */
function PlayVideos(dats, host) {
	if (!dats || dats.length <= 0)
		return;
	hClearFlvHls();
	if (dats.length == 1) {
		var dat = dats[0];
		PlayVideo(dat.id, dat.code, host);
		return;
	}
	var pid = "mcams";
	var dom = document.querySelector("#" + pid);
	var box;
	if (!dom) {
		dom = createVideoDom(pid);
		dom.addEventListener("mousedown", hMouseDown, false);
		//dom.lastChild().remove(true);
		dom.children[1].remove();
		box = document.createElement("div");
		box.setAttribute("class", 'panels');
		dom.appendChild(box);
	} else {
		box = dom.children[1];
	}

	var vhtml = "";
	for (var i = 0; i < dats.length; i++) {
		var dat = dats[i];
		vhtml += `<div>
					<video id="v2_${dat.id}" class="videoPlayer" controls muted loop autoplay></video>
					<label>cam_${dat.id}</label>
				</div>`;
	}
	box.innerHTML = vhtml;
	ShowPanel(pid);

	for (var i = 0; i < dats.length; i++) {
		var dat = dats[i];

		if (use == camtypes.flv_hls) {
			var domvideo = document.querySelector("#v2_" + dat.id);
			hHlsPlay(host, dat.code, domvideo);
		} else {
			var v2 = new WebRtcPlayer("v2_" + dat.id, 'demo');
			var v3 = {
				id: dat.id,
				video: v2
			};
			v2s.push(v3);
			v2.load(dat.code);
		}
	}

}

var _arrHlsFlv = [];

const hlTp = {
	hls: 'hls',
	flv: 'flv'
};

function hHlsPlay(ip, channelCode, domVideo, st) {
	var hlsTemplate = "http://{0}:7086/live/cameraid/{1}%24{2}/substream/{3}.m3u8";

	ip = ip || "192.168.100.2";
	if (!channelCode) {
		console.warn("监控打开失败。编码异常。" + channelCode);
		return;
	}
	let id = domVideo.id;

	//var channelCode=$("#channelCode").val();
	var deviceCode = channelCode.substr(0, channelCode.indexOf("$"));
	var channelSeq = channelCode.substr(channelCode.lastIndexOf("$") + 1);
	var sustreamType = st ? st : 1; //1主码流，2辅码流
	var url = String.format(hlsTemplate, ip, deviceCode, channelSeq, sustreamType);

	let obj = _arrHlsFlv.find(t => t.id == id),
		oPlay = obj ? obj.v : null,
		tp = isHlsFlv(url);
	if (hlTp.hls == tp) {
		if (!oPlay) {
			oPlay = new Hls();
		}
		oPlay.loadSource(url);
		oPlay.attachMedia(domVideo);
		oPlay.on(Hls.Events.MANIFEST_PARSED, function() {
			domVideo.play();
		});

	} else if (tp == hlTp.flv) {
		if (!oPlay) {
			oPlay = flvjs.createPlayer({
				type: 'flv',
				url: url
			});
		}
		oPlay.attachMediaElement(domVideo);
		oPlay.load();
		oPlay.play();

	} else {
		console.log("错误类型地址")
		return;
	}
	if (!obj) {
		_arrHlsFlv.push({
			id: id,
			v: oPlay,
			t: tp
		});
	} else if (obj.v == null) {
		obj.v = oPlay;
	}
}

function isHlsFlv(url) {
	var extension = url.substring(url.lastIndexOf('.') + 1);

	if ("m3u8" == extension.toLowerCase()) {
		return "hls";
	}
	if ("flv" == extension.toLowerCase()) {
		return "flv";
	}
	return "";
}


function hClearFlvHls(vid) {

	for (var i = 0; i < _arrHlsFlv.length; i++) {
		let obj = _arrHlsFlv[i];
		let ov = obj.v;
		if (obj.id == vid) {

			switch (obj.t) {
				case hlTp.flv:
					ov.unload();
					ov.detachMediaElement();
					ov.destroy();
					break;
				case hlTp.hls:
					ov.destroy();
					break;
				default:
			}
			obj.v = null;
			_arrHlsFlv = [..._arrHlsFlv.slice(0, i), ..._arrHlsFlv.slice(i + 1)];
			return;
		}
	}
}


switch (use) {
	case camtypes.rtc:
		hWaitWebRtc();
		break;
	case camtypes.flv_hls:
		hWaitFlvHls();
		break;
	default:
		break;
}
